import { getAccountPage } from '@/services/api/api-admin-account';
import { treeOrganization } from '@/services/api/api-admin-organization';

import { FolderOutlined } from '@ant-design/icons';
import ProCard from '@ant-design/pro-card';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Drawer, Space, Tag, Tree } from 'antd';
import { DataNode } from 'antd/lib/tree';
import { useEffect, useRef, useState } from 'react';
interface PreviewUserProps { }

const PreviewUser: React.FC<PreviewUserProps> = ({ }) => {
  const [drawerFormOpen, setDrawerFormOpenState] = useState(false);
  const userRef = useRef<ActionType>();
  const columns: ProColumns<AdminAccountData.Account>[] = [
    {
      title: '账号',
      key: 'name',
      dataIndex: 'name',
      width: '80px',
      fixed: 'left',
      render: (_, row) => {
        return (
          <div>
            <span style={{ color: row.state === 0 ? '#FF4D4F' : '#5B8FF9' }}>{row.name}</span>
          </div>
        );
      },
    },
    {
      title: '电话',
      key: 'phone',
      dataIndex: 'phone',
      width: '120px',
    },
    {
      title: '组织',
      key: 'organizationName',
      dataIndex: 'organizationName',
      width: '180px',
      render: (_, row) => (
        <Space size={[0, 'small']} wrap>
          <Tag key={row.id + row.phone}>{row.organizationName}</Tag>
        </Space>
      ),
    },
    {
      title: '最后登录时间',
      key: 'loginTime',
      dataIndex: 'loginTime',
      hideInSearch: true,
      width: 150,
    },
  ];

  /**
   * 初始化树形数据(用户数据)
   */
  const [dataTree, setDataTreeState] = useState<DataNode[]>();

  /**
   * 树形列表选择数据
   */
  const [dataTreeSelect, setTreeDataSelectState] = useState<UserData.Organization>({
    name: '融媒通',
  });

  useEffect(() => {
    previewTreeOrganizationData();
  }, []);

  /**
   * 本月选题计划
   */
  const previewTreeOrganizationData = async () => {
    try {
      const response = await treeOrganization();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '融媒通',
          key: '0',
          item: { id: '0', name: '融媒通' },
          children: readyTreeData(response.data),
        });
        setDataTreeState(treeData);
      }
    } catch (error) { }
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: Array<UserData.Organization>): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val, idx, array) => {
        treeData.push({
          title: val.name,
          key: val.id,
          type: val.type,
          children: readyTreeData(val.children as Array<UserData.Organization>),
          icon: <FolderOutlined />,
        });
      });
    }
    return treeData;
  }



  return (
    <>
      <Drawer
        title={'选择组织单位'}
        open={drawerFormOpen}
        onClose={() => setDrawerFormOpenState(false)}
        width={400}
      // onOpenChange={(visible: boolean) => setDrawerFormOpenState(visible)}
      >
        <ProCard
          title={
            <div style={{ display: 'flex' }}>
              <div
                style={{
                  backgroundImage: 'linear-gradient(98deg,#A9D5FC,#A6CDFB)',
                  padding: 10,
                  width: 300,
                  marginLeft: '-25px',
                  borderRadius: 5,
                }}
              >
                <span>组织单位</span>
              </div>
            </div>
          }
          colSpan={'20%'}
          bordered={false}
          direction={'row'}
        >
          {dataTree && dataTree.length ? (
            <Tree
              defaultExpandedKeys={['0']}
              height={637}
              showLine={{ showLeafIcon: false }}
              showIcon={true}
              treeData={dataTree}
              onSelect={(selectedKeys: React.Key[], info: any) => {
                if (info.node.pos.length == 3 && info.selected) {
                  setTreeDataSelectState({
                    id: '',
                    type: info.node.type,
                    name: info.node.title,
                  } as UserData.Organization);
                } else if (info.selected) {
                  setTreeDataSelectState({
                    id: info.node.key,
                    type: info.node.type,
                    name: info.node.title,
                  } as UserData.Organization);
                  // loadOrganizationItemData(info.node.key);
                } else {
                  setTreeDataSelectState({
                    id: '0',
                    name: '融媒通',
                  } as UserData.Organization);
                }
                setDrawerFormOpenState(!drawerFormOpen);
                userRef.current?.reset();
              }}
            />
          ) : (
            '暂无数据'
          )}
        </ProCard>
      </Drawer>
      <ProCard>
      </ProCard>
      <ProTable<AdminAccountData.Account>
        // cardProps={false}
        actionRef={userRef}
        columns={columns}
        request={async (params = {}) => {
          const response = await getAccountPage({
            ...params,
            isHide: 0,
            organizationId: dataTreeSelect?.id,
            organizationType: dataTreeSelect?.type,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        dateFormatter="string"
        bordered
        // search={{
        //   filterType: 'light',
        // }}
        search={false}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 10,
        }}
        options={false}
        headerTitle={
          <div
            style={{
              display: 'inline-block',
              color: '#5B8FF9',
            }}
            onClick={() => setDrawerFormOpenState(true)}
          >
            {dataTreeSelect?.name}
          </div>
        }
      />
    </>
  );
};

export default PreviewUser;
